package cn.snorlaxzjt.LBSserver.service;

import cn.snorlaxzjt.LBSserver.common.BusinessCode;
import cn.snorlaxzjt.LBSserver.common.EmailConfig;
import cn.snorlaxzjt.LBSserver.common.Result;
import cn.snorlaxzjt.LBSserver.mapper.UserMapper;
import cn.snorlaxzjt.LBSserver.po.entity.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.regex.Pattern;

@Service
public class EmailService {

    @Resource
    UserMapper userMapper;

    final String u = "^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$";

    public Result<Void> checkEmail(String address){
        if(!Pattern.matches(u, address)){
            return BusinessCode.EMAIL_VALIDATE_FAILED.toResult();

        }
        String existUser= userMapper.findUserByEmail(address);
        if(existUser != null){
            //如果邮箱已存在
            return BusinessCode.EMAIL_EXIST.toResult();
        }
        return BusinessCode.SUCCESS.toResult();
    }

    public boolean sendEmail(String receiver)
    {
        try
        {
            Properties properties = new Properties();
            properties.setProperty("mail.host", "smtp.qq.com");
            properties.setProperty("mail.transport.protocol", "smtp");
            properties.setProperty("mail.smtp.auth", "true");
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.smtp.port", "465");
            Session session = Session.getDefaultInstance(properties);
            session.setDebug(true);
            MimeMessage mimeMessage = new MimeMessage(session);
            String Number= EmailConfig.RandomSix();
            mimeMessage.addRecipients(Message.RecipientType.TO, receiver);//设置收信人
            mimeMessage.setFrom(new InternetAddress(EmailConfig.Sender,"卡比兽注册机器人"));//邮件发送人
            mimeMessage.setSubject("验证码");//邮件主题
            mimeMessage.setContent("Hello,您的验证码为 : "+Number, "text/html;charset=utf-8");//正文
            Transport transport = session.getTransport();
            transport.connect("smtp.qq.com", EmailConfig.Sender, EmailConfig.password);
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());//发送邮件，第二个参数为收件人
            transport.close();
            EmailConfig.cache.put(receiver,Number);
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }
}
